/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.forum.post;

import com.blandware.atleap.common.ForumModuleConstants;
import com.blandware.atleap.model.forum.Forum;
import com.blandware.atleap.model.forum.Post;
import com.blandware.atleap.model.forum.Topic;
import com.blandware.atleap.service.forum.ForumManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.forum.PostForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebConstants;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>Shows a post.</p>
 * <p><a href="ShowPostAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.6 $ $Date: 2008/04/29 17:51:51 $
 * @struts.action path="/forum/post/show"
 * name="postForm"
 * scope="request"
 * validate="false"
 * @struts.action-forward name="showPost"
 * path=".forum.post.show"
 * @struts.action-forward name="showTopic"
 * path="/forum/topic/show.do"
 * redirect="true"
 * @struts.action-forward name="showForum"
 * path="/forum/forum/show.do"
 * redirect="true"
 */
public final class ShowPostAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
		PostForm postForm = (PostForm) form;
		Long postId = null;
		if ( !GenericValidator.isBlankOrNull(postForm.getId()) ) {
			postId = Long.valueOf(postForm.getId());
		} else if ( session.getAttribute(ForumModuleWebConstants.POST_ID_KEY) != null ) {
			postId = (Long) session.getAttribute(ForumModuleWebConstants.POST_ID_KEY);
		}

        session.setAttribute(ForumModuleWebConstants.POST_ID_KEY, postId);

        ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
        Post post = null;
        Topic topic = null;
        Forum forum = null;

        if (postId == null) {
			// post ID not found
            if (log.isDebugEnabled()) {
                log.debug("No post ID was found; going back to post");
            }
			return mapping.findForward("showTopic");
        }

        post = forumManager.retrievePost(postId);
        if ( post == null ) {
			// post not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("postNotFound", new ActionMessage("forum.post.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("showTopic");
        }

        Long topicId = post.getTopic().getId();
        topic = forumManager.retrieveTopic(topicId);
        if ( topic == null ) {
            ActionMessages errors = new ActionMessages();
            errors.add("ownerNotFound", new ActionMessage("forum.post.errors.ownerNotFound"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        }

        session.setAttribute(ForumModuleWebConstants.TOPIC_ID_KEY, topicId);

        Long forumId = topic.getForum().getId();
        forum = forumManager.retrieveForum(forumId);
        if ( forum == null ) {
            ActionMessages errors = new ActionMessages();
            errors.add("ownerNotFound", new ActionMessage("forum.topic.errors.ownerNotFound"));
            saveErrors(request, errors);
            session.removeAttribute(ForumModuleWebConstants.FORUM_ID_KEY);
            return mapping.findForward("showForum");
        }

        session.setAttribute(ForumModuleWebConstants.FORUM_ID_KEY, forumId);

        if ( !forum.getActive().booleanValue() || !post.getActive().booleanValue() ) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return null;
        }

        List forumRoles = forum.getRoles();
        List postRoles = post.getRoles();
        if (!WebappUtil.isUserInRole(forumRoles, false, "name", request)
                || !WebappUtil.isUserInRole(postRoles, false, "name", request)) {
            // access denied
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        List forums = ForumModuleWebUtil.getForumParentsList(forum,
                                                             forumManager);
        session.setAttribute(ForumModuleWebConstants.FORUM_PARENTS_LIST_KEY,
                             forums);
        session.setAttribute(ForumModuleWebConstants.PARENT_TOPIC_KEY, topic);

        request.setAttribute(WebappConstants.DISPLAYED_OBJECT_URI_KEY,
                             post.getUri());

		// save transaction token in request
		saveToken(request);

		request.setAttribute("currentForum", forum);
        request.setAttribute("currentTopic", post);
        request.setAttribute("currentPost", post);
		return mapping.findForward("showPost");
	}
}
